//
//  HJCityManager.m
//  project
//
//  Created by jc on 2019/4/12.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJCityManager.h"

@implementation HJCityManager

+(instancetype)manager {
    static HJCityManager * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    return instance;
}

-(void)cityDataSourceWithHeadTitles:(void (^)(NSArray * _Nonnull, NSDictionary * _Nonnull))headTitles {
    NSArray * keyArray = [[[self getAllCityDic] allKeys] sortedArrayUsingSelector:@selector(compare:)];
    if (headTitles) {
        headTitles(keyArray,[self getAllCityDic]);
    }
}

// 本地总城市数
-(NSDictionary *)getAllCityDic {
    NSMutableDictionary * cityAllDic =[NSMutableDictionary dictionary];
    NSMutableArray * arr = [NSMutableArray array];
    for (NSDictionary * cityDic in [self cityJson]) {
        NSString * firstLetter = [CommonTools getFirstLetterFromString:cityDic[@"cityName"]];
        if ([[cityAllDic allKeys] containsObject:firstLetter]) {// 包含
            arr = [cityAllDic objectForKey:firstLetter];
            [arr addObject:cityDic];
            [cityAllDic setObject:arr forKey:firstLetter];
        }else {// 不包含
            arr = [[NSMutableArray alloc]initWithObjects:cityDic, nil];
            [cityAllDic setObject:arr forKey:firstLetter];
        }
    }
    return cityAllDic;
}
#pragma mark-- 热门城市
-(void)loadRequestWithSuccess:(void (^)(NSArray * _Nonnull))success {
    NSMutableArray * hotArray = [NSMutableArray array];
    NSString * url = [Api stringByAppendingString:HotCityListApi];
    [HJHttpTool post:url params:nil success:^(HJResponeds *result) {
        [hotArray removeAllObjects];
        [hotArray addObjectsFromArray:result.data];
        if (success) {
            success(hotArray);
        }
    } failure:^(id result) {
    }];
}

-(NSArray *)cityJson {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"cityList" ofType:@"json"];
    NSError * error;
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableContainers error:&error];
    NSArray * dicArr = dic[@"data"];
    if (dicArr.count==0) return nil;
    NSMutableArray * dataSource = [NSMutableArray array];
    for (NSDictionary * cityDic in dicArr) {
        if ([cityDic[@"cityLevel"] isEqual:@2]) {
            [dataSource addObject:cityDic];
        }
    }
    return dataSource;
}

-(NSInteger)cityIdWithFormCity:(NSString *)city {
    NSInteger cityID = 0;
    NSDictionary * cityDic = [self getAllCityDic];
    for (NSArray * cityDicValues in [cityDic allValues]) {
        for (NSDictionary * cityValueDic in cityDicValues) {
            if ([cityValueDic[@"cityName"] isEqualToString:city]) {
                cityID = [cityValueDic[@"cityOid"] integerValue];
                break;
            }
        }
    }
    return cityID;
}

@end
